from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.db import connection, transaction
from django.contrib.auth.decorators import login_required


from hotels.models import Hotel
from rooms.models import Room
from rooms.models import RegRooms


from datetime import datetime

# Create your views here.
def index(request):

	return render(request, 'hotels/index.html')
	

def viewpics(request):
	context = {'pic':'1.jpg',}
	return render(request, 'hotels/viewpics.html', context)


def search(request):

	if 'user_id' not in request.session:
		return redirect('/users/login/')

	if request.method == 'POST':
		hotel = request.POST['hotel']
		city = request.POST['city']
		country = request.POST['country']
		room_type = request.POST['room_type']
		chkin_date = request.POST['chkin_date']
		chkout_date = request.POST['chkout_date']

		print "%s , %s , %s , %s , %s , %s" %(hotel, city, country, room_type, chkin_date, chkout_date)
		
		hotels_list = ""

		if hotel != "" and city == "" and country == "":
			try:
				hotels_list = Hotel.objects.filter(name=hotel)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"

		elif hotel != "" and city != "" and country == "":
			try:
				hotels_list = Hotel.objects.filter(name=hotel, city=city)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"

		elif hotel != "" and city =="" and country != "":
			try:
				hotels_list = Hotel.objects.filter(name=hotel, country=country)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"

		
		elif hotel != "" and city != "" and country != "" :
			try:
				hotels_list = Hotel.objects.filter(name=hotel, city=city, country=country)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"

		elif hotel == "" and city !="" and country == "":
			try:
				hotels_list = Hotel.objects.filter(city=city)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"
		
		elif hotel == "" and city =="" and country != "":
			try:
				hotels_list = Hotel.objects.filter(country=country)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"

		elif hotel == "" and city !="" and country != "":
			try:
				hotels_list = Hotel.objects.filter(city=city, country=country)
			except Hotel.DoesNotExist:
				hotels_list = False
				print "Not Found"

		else:
			context = {'error_message':'No Search Criteria Entered.'}
			return render(request, 'hotels/index.html', context)
	

		rooms = []
	
		if chkin_date != "" and chkout_date != "" :
		
			cid = datetime.strptime(chkin_date, "%Y-%m-%d").date()
			cod = datetime.strptime(chkout_date, "%Y-%m-%d").date()

			if cid < cod:
				if hotels_list is not False:
					room = None
					for hotel in hotels_list:
						room = None
						for room in RegRooms.objects.raw("SELECT * FROM rooms_room, hotels_hotel WHERE rooms_room.hotel_id_id = %s AND rooms_room.room_type = '%s' AND rooms_room.hotel_id_id = hotels_hotel.id AND rooms_room.id NOT IN (SELECT rooms_regrooms.room_id_id FROM rooms_regrooms WHERE rooms_regrooms.chkin_date BETWEEN '%s' AND '%s' AND rooms_regrooms.chkout_date BETWEEN '%s' AND '%s')" % (int(hotel.id), str(room_type), str(chkin_date), str(chkout_date), str(chkin_date), str(chkout_date)) ):
							
							rooms.append(room)
							context = {'rooms_list' : rooms, 'chkin_date' : chkin_date, 'chkout_date' : chkout_date}
							return render(request, 'hotels/found_hotels.html', context)
							
					if room is None:
						context = {'error_message':'No Empty Rooms Found.'}
						return render(request, 'hotels/index.html', context)
		
				else:
					context = {'error_message':'No Hotels Found.'}
					return render(request, 'hotels/index.html', context)
				
			else:
				context = {'error_message':'ERROR : Checkin Date Is After Checkout Date'}
				print "false"
				return render(request, 'hotels/index.html', context)
		else:
			context = {'error_message':'Please Select Checkin Date And Checkout Date'}
			print "false"
			return render(request, 'hotels/index.html', context)

	return render(request, 'hotels/index.html')


def reserve(request, room_id='', hotel_id='', chkin_date='', chkout_date=''):

	if 'user_id' not in request.session:
		return redirect('/users/login/')

	user_id = request.session['user_id']
	insert_flag = None
	#insert_flag = RegRooms.objects.create(room_id=int(room_id), hotel_id=int(hotel_id), user_id=8, chkin_date=str(chkin_date), chkout_date=str(chkout_date))
	
	cursor = connection.cursor()
		
	insert_flag = None
	insert_flag = cursor.execute("INSERT INTO booking_site.rooms_regrooms (room_id_id, hotel_id_id, user_id_id, chkin_date, chkout_date) VALUES ('%s', '%s', '%s', '%s', '%s')" % (room_id, hotel_id, user_id, chkin_date, chkout_date ))
	
	
	if insert_flag is None:
		return HttpResponse('Reserved')
	else:
		return HttpResponse('Error')



def dump(obj):
   for attr in dir(obj):
       if hasattr( obj, attr ):
           print( "obj.%s = %s" % (attr, getattr(obj, attr)))


def get_current_path(request):
    return {
       'current_path': request.get_full_path()
     }
